package com.asm.controller;

import com.asm.mapper.*;
import com.asm.pojo.*;
import com.asm.service.Analysis2With3DService;
import com.asm.service.SNV2TfCHIPseqService;
import com.asm.service.SnvCpgAllService;
import com.asm.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
public class SearchController {
    @Autowired
    private Path path;
    @Autowired
    private ExecLinux execLinux;
    @Autowired
    private SNV2TfCHIPseqMapper snv2TfChipSeqMapper;
    @Autowired
    private SNV2TfCHIPseqService snv2TfCHIPseqService;

    @Autowired
    private Analysis2With3DMapper analysis2With3DMapper;
    @Autowired
    private Analysis2With3DService analysis2With3DService;
    @Autowired
    private Analysis1SigMapper analysis1SigMapper;
    @Autowired
    private SnvCpgAllService snvCpgAllService;
    @Autowired
    private SnvCpgAllMapper snvCpgAllMapper;
    @Autowired
    private CpgGeneFiltMapper cpgGeneFiltMapper;

    @GetMapping("/tf/search")
    public DatatableResult<Analysis1Sig> TFBindingAlterationList(@RequestParam("tf")String tf,
                                                                 @RequestParam("health_status")String health_status,
                                                                 @RequestParam(value = "snv",required = false) String snv,
                                                                 @RequestParam( value = "type",defaultValue = "tf") String type,
                                                                 @RequestParam("tissue") String tissue,
                                                                 @RequestParam("motif") String motif,
                                                                 @RequestParam("start") int start,
                                                                 @RequestParam("length") int length,
                                                                 @RequestParam("search") String search){
        System.out.println("tf "+health_status+" "+length);
        System.out.println("tf "+motif);
        List<Analysis1Sig> list = null;
        String[] health = health_status.split(",");
//        for (String item : health) {
//            System.out.println("tf health "+item+" "+length);
//        }
        DatatableResult<Analysis1Sig> datatableResult = new DatatableResult<>();
        if(tissue.equals("ALL")){
            tissue = null;
        }
        if (type.equals("snv")){
            tf = null;
        }else {
            snv = null;
        }
        PageHelper.startPage(start, length);
        if (motif.equals("Jspar_validated")){
            motif = "Jaspar2024";
            list = analysis1SigMapper.getTFBindingAlterationCor(tf,health,tissue,motif,snv,search);
        } else if (motif.equals("Jspar_predicted")) {
            motif = "Jaspar2024";
            list = analysis1SigMapper.getTFBindingAlterationPre(tf,health,tissue,motif,snv,search);

        } else if(motif.equals("HOCOMOCOv12core")){
            motif = "HOCOMOCOv12";
            list = analysis1SigMapper.getTFBindingAlterationHoCore(tf,health,tissue,motif,snv,search);
        } else if(motif.equals("HOCOMOCOv12invitro")){
            motif = "HOCOMOCOv12";
            list = analysis1SigMapper.getTFBindingAlterationHoinvitro(tf,health,tissue,motif,snv,search);
        }else if(motif.equals("HOCOMOCOv12invivo")){
            motif = "HOCOMOCOv12";
            list = analysis1SigMapper.getTFBindingAlterationHoinvivo(tf,health,tissue,motif,snv,search);
        }else if(motif.equals("HOCOMOCOv12rSNP")){
            // HOCOMOCOv12rSNP
            motif = "HOCOMOCOv12";
            list = analysis1SigMapper.getTFBindingAlterationHorSNP(tf,health,tissue,motif,snv,search);
        }
        PageInfo<Analysis1Sig> pageInfo = new PageInfo<>(list,length);
        datatableResult.setDraw(datatableResult.getDraw());
// stream流去重
        datatableResult.setData(pageInfo.getList().stream().distinct().collect(Collectors.toList()));
        datatableResult.setRecordsTotal((int) pageInfo.getTotal());
        datatableResult.setRecordsFiltered(datatableResult.getRecordsTotal());
        return datatableResult;
    }

    @GetMapping("/snv_cpg/search")
    public DatatableResult<SnvCpgAll> snvCpgAllList(
            @RequestParam("tissue") String tissue,
            @RequestParam("sampleType") String sampleType,
            @RequestParam("chr") String chr,
            @RequestParam("search") String search,
            @RequestParam("start") int start,
            @RequestParam("length") int length){
        DatatableResult<SnvCpgAll> datatableResult = new DatatableResult<>();
        PageHelper.startPage(start, length);
        System.out.println("tissue: " + tissue);
        System.out.println("sampleType: " + sampleType);
        System.out.println("chr: " + chr);
        List<SnvCpgAll> list = snvCpgAllService.selectAllSnvCpgAllBySearch(tissue, sampleType, chr,search);
        PageInfo<SnvCpgAll> pageInfo = new PageInfo<>(list);
        datatableResult.setDraw(datatableResult.getDraw());
        datatableResult.setData(pageInfo.getList());
        datatableResult.setRecordsTotal((int) pageInfo.getTotal());
        datatableResult.setRecordsFiltered(datatableResult.getRecordsTotal());
        return datatableResult;
    }

    @GetMapping("/tf_chip-seq/search")
    public DatatableResult<SNV2TfCHIPseq> TFChipSeqBindingList(@Param("tfName") String tfName,
                                                               @RequestParam(value = "snv",required = false) String snv,
                                                               @RequestParam( value = "type",defaultValue = "tf") String type,
                                                               @RequestParam("start") int start,
                                                               @RequestParam("length") int length,
                                                               @RequestParam("health_status")String health_status,
                                                               @RequestParam("tissue") String tissue,
                                                               @RequestParam("search")String search){
        if (type.equals("tf")){
            snv = null;
        }else{
            tfName = null;
        }
        if (tissue.equals("ALL")){
            tissue = null;
        }
        String[] status = health_status.split(",");
        DatatableResult<SNV2TfCHIPseq> datatableResult = new DatatableResult<>();
        List<SNV2TfCHIPseq> list = snv2TfCHIPseqService.getChIPseqAnalysis1BySearch(tfName,snv,status,tissue,search);
        int totalSize = list.size();
        int fromIndex = (start-1) * length;
        int toIndex = Math.min(fromIndex + length, totalSize);
        if (fromIndex >= totalSize) {
            datatableResult.setData(Collections.emptyList()); // 如果页面超出范围，返回空列表
        }
        datatableResult.setDraw(datatableResult.getDraw());
        datatableResult.setData(list.subList(fromIndex, toIndex));
        datatableResult.setRecordsTotal(totalSize);
        datatableResult.setRecordsFiltered(datatableResult.getRecordsTotal());
        return datatableResult;
    }

    @GetMapping("/tf_snv_alterating/search")
    public DatatableResult<SnvCpgAll> TFSnvAlteratingList(@RequestParam("tf")String tf,
                                                          @RequestParam("health_status")String health_status,
                                                          @RequestParam(value = "snv",required = false) String snv,
                                                          @RequestParam( value = "type",defaultValue = "tf") String type,
                                                          @RequestParam("tissue") String tissue,
                                                          @RequestParam("motif") String motif,
                                                          @RequestParam("start") int start,
                                                          @RequestParam("length") int length,
                                                          @RequestParam("search") String search){
        System.out.println("tf_snv "+tf+" "+length);
        List<Analysis1Sig> rsList = null;
        String[] health = health_status.split(",");

        if(tissue.equals("ALL")){
            tissue = null;
        }
        if (type.equals("snv")){
            tf = null;
        }else {
            snv = null;
        }
//        if (motif.equals("Jspar_validated")){
//            rsList = analysis1SigMapper.getTFBindingAlterationCorDeduplication(tf,health,tissue,null,snv);
//
//        } else if (motif.equals("Jspar_predicted")) {
//            rsList = analysis1SigMapper.getTFBindingAlterationPreDeduplication(tf,health,tissue,null,snv);
//
//        } else if (motif.equals("HOCOMOCOv12core")){
//            rsList = analysis1SigMapper.getTFBindingAlterationHoPreDeduplication(tf,health,tissue,null,snv);
//        }else if(motif.equals("HOCOMOCOv12invitro")){
//            rsList = analysis1SigMapper.getTFBindingAlterationHoinvitroDeduplication(tf,health,tissue,null,snv);
//        }else if(motif.equals("HOCOMOCOv12invivo")){
//            rsList = analysis1SigMapper.getTFBindingAlterationHoinvivoDeduplication(tf,health,tissue,null,snv);
//        }else if(motif.equals("HOCOMOCOv12rSNP")){
//            // HOCOMOCOv12rSNP
//            rsList = analysis1SigMapper.getTFBindingAlterationHorsnpDeduplication(tf,health,tissue,null,snv);
//        }
        if (motif.equals("Jspar_validated")){
            motif = "Jaspar2024";
            rsList = analysis1SigMapper.getTFBindingAlterationCor(tf,health,tissue,motif,snv,search);
        } else if (motif.equals("Jspar_predicted")) {
            motif = "Jaspar2024";
            rsList = analysis1SigMapper.getTFBindingAlterationPre(tf,health,tissue,motif,snv,search);

        } else if(motif.equals("HOCOMOCOv12core")){
            motif = "HOCOMOCOv12";
            rsList = analysis1SigMapper.getTFBindingAlterationHoCore(tf,health,tissue,motif,snv,search);
        } else if(motif.equals("HOCOMOCOv12invitro")){
            motif = "HOCOMOCOv12";
            rsList = analysis1SigMapper.getTFBindingAlterationHoinvitro(tf,health,tissue,motif,snv,search);
        }else if(motif.equals("HOCOMOCOv12invivo")){
            motif = "HOCOMOCOv12";
            rsList = analysis1SigMapper.getTFBindingAlterationHoinvivo(tf,health,tissue,motif,snv,search);
        }else if(motif.equals("HOCOMOCOv12rSNP")){
            // HOCOMOCOv12rSNP
            motif = "HOCOMOCOv12";
            rsList = analysis1SigMapper.getTFBindingAlterationHorSNP(tf,health,tissue,motif,snv,search);
        }
        DatatableResult<SnvCpgAll> datatableResult = new DatatableResult<>();
        PageHelper.startPage(start, length);

        List<SnvCpgAll> list = new ArrayList<>();
        if (!rsList.isEmpty()){
            list = snvCpgAllMapper.selectTFbindingByRsList(rsList.stream().distinct().collect(Collectors.toList()));
        }
        PageInfo<SnvCpgAll> pageInfo = new PageInfo<>(list,length);
        datatableResult.setDraw(datatableResult.getDraw());
        datatableResult.setData(pageInfo.getList().stream().distinct().collect(Collectors.toList()));
        datatableResult.setRecordsTotal((int) pageInfo.getTotal());
        datatableResult.setRecordsFiltered(datatableResult.getRecordsTotal());
        return datatableResult;
    }

    @GetMapping("/home/snv/search")
    public List<SnvCpgAll> HomeSnvSearchList(@RequestParam("search") String search){
        List<SnvCpgAll> list = snvCpgAllMapper.selectHomeSNVFromAllSnvCpgAllBySearch(search);
        return list;
    }

    @GetMapping("/home/gene/search")
    public List<SnvCpgAll> HomeGeneSearchList(@RequestParam("search") String search){
        List<CpgGeneFilt> snvList = cpgGeneFiltMapper.getSNVByGene(search);
        List<String> rList = snvList.stream()
                .map(s -> s.getSnv())
                .distinct()
                .collect(Collectors.toList());
        List<SnvCpgAll> list = snvCpgAllMapper.selectHomeSNVFromAllSnvCpgAllByRsList(rList);
        return list;
    }

    @GetMapping("/home/genonmic_region/search")
    public List<SnvCpgAll> HomeGenonmicRegionSearchList(@RequestParam("search") String search) throws IOException {
//        List<CpgGeneFilt> snvList = cpgGeneFiltMapper.getSNVByGene(search);
        // 返回值文件提取
        File file_genonmic =new File("./genonmic_region.bed");
        if(!file_genonmic.exists()){
            file_genonmic.createNewFile();
        }
        BufferedWriter bw2 = new BufferedWriter(new FileWriter(file_genonmic,false));
        String[] genonmic = DataHandle.getChrSnpposCpgpos(search);
        System.out.println("genonmic[0] ='" + genonmic[0] + "'");
        System.out.println("genonmic[1] ='" + genonmic[1] + "'");
        System.out.println("genonmic[2] ='" + genonmic[2] + "'");
        StringBuilder Row = new StringBuilder();
        Row.append(genonmic[0].trim())
                .append("\t")
                .append(genonmic[1].trim())
                .append("\t")
                .append(genonmic[2].trim());
        bw2.write(Row.toString().trim());
        bw2.newLine();
        bw2.close();
        //上传文件
        String path =this.path.getFileUploadPath();
        String randomName_chrom = UUID.randomUUID().toString();
        String resultName = randomName_chrom +".bed";
        String fileName_genonmic = FileFr.upload(path,randomName_chrom,".bed",FileFr.fileMultipartFile(file_genonmic));

        //上传r执行命令
        String command = null;
        try {
            Shell shell = new Shell(execLinux);
//            command = shell.execCommand("conda activate base;cd /home/CanASM/runfile/static;bedtools intersect -a snv_cpg.bed -b /home/CanASM/runfile/uploadfile/"+fileName_genonmic+" > /home/CanASM/runfile/resultfile/"+resultName);
            command = shell.execCommand("conda activate base;cd /home/jmzhao/CanASM/runfile/static;bedtools intersect -a snv_cpg.bed -b /home/jmzhao/CanASM/runfile/uploadfile/"+fileName_genonmic+" > /home/jmzhao/CanASM/runfile/resultfile/"+resultName);

        } catch (Exception e) {
            e.printStackTrace();
        }

        String fileResultpath =this.path.getResultFilePath()+resultName;
        File file = new File(fileResultpath);
        BufferedReader br = new BufferedReader(new FileReader(file));
        String s,index = "";
        while ((s = br.readLine()) != null) {
            String[] sline = s.split("\n");
            String[] sIndex = sline[0].split("\t");
//            int num = Integer.parseInt(sIndex[3]);
            String formattedNum = sIndex[3].toString();
            index = formattedNum + "," + index;
        }
        br.close();
        String[] indexId = index.split(",");
//        写的啥啊，冗余查询
//        List<Analysis2With3D> Distal = analysis2With3DService.getDistal(indexId,1,1000000);
//        List<Analysis2With3D> Proximal = analysis2With3DService.getProximal(indexId,1,1000000);
//        List<CpgGeneFilt> snvList = new ArrayList<CpgGeneFilt>();
//        for (Analysis2With3D snvId: Distal) {
//            CpgGeneFilt cpgGeneFilt = new CpgGeneFilt();
//            cpgGeneFilt.setSnv(snvId.getSnv());
//            snvList.add(cpgGeneFilt);
//        }
//        for (Analysis2With3D snvId: Proximal) {
//            CpgGeneFilt cpgGeneFilt = new CpgGeneFilt();
//            cpgGeneFilt.setSnv(snvId.getSnv());
//            snvList.add(cpgGeneFilt);
//        }

        List<String> rList = Arrays.stream(indexId).distinct().collect(Collectors.toList());
        System.out.println("rList=====>"+rList);
        List<SnvCpgAll> list ;
        list = snvCpgAllMapper.selectHomeSNVFromAllSnvCpgAllByRsList(rList);
//        if (snvList == null || snvList.isEmpty()) {
//            throw new IllegalArgumentException("rsList must not be empty");
//        }
        file_genonmic.delete();
        return list;
    }
}
